﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bowling.Test
{
    public class Scorer
    {
        private RollRecord _rollRecord;
        public Scorer(RollRecord rollRecord)
        {
            _rollRecord = rollRecord;
        }

        public void UpdateFrameScores()
        {
            int totalScore = 0;

            for (int i = 0; i < 10; i++)
            {
                var frame = _rollRecord.Frames[i];
                int roll1 = frame.Roll1;
                int roll2 = frame.Roll2 ?? 0;
                int bonus = frame.Bonus ?? 0;

                if (roll1 + roll2 < 10)
                {
                    totalScore = ScoreSimple(frame, roll1, roll2, totalScore);
                    continue;
                }

                if (roll1 != 10 && (roll1 + roll2 == 10))
                {
                    totalScore = ScoreSpare(frame, roll1, roll2, totalScore);
                    continue;
                }

                if (roll1 == 10)
                {
                    totalScore = ScoreStrike(frame, totalScore);
                    continue;
                }
            }
        }


        private int NextBall(int currentBallIndex)
        {
            return _rollRecord.Rolls[currentBallIndex];
        }

        private int NextTwoBalls(int currentBallIndex)
        {
            return _rollRecord.Rolls[currentBallIndex] + _rollRecord.Rolls[currentBallIndex + 1];
        }


        private int ScoreSimple(Frame frame, int roll1, int roll2, int totalScore)
        {
            frame.Score.RollScore = roll1 + roll2;
            totalScore = totalScore + frame.Score.RollScore;
            frame.Score.TotalScore = totalScore;
            return totalScore;
        }

        private int ScoreStrike(Frame frame, int totalScore)
        {
            frame.Score.RollScore = 10 + NextTwoBalls(frame.Roll1BallIndex + 1);
            totalScore = totalScore + frame.Score.RollScore;
            frame.Score.TotalScore = totalScore;
            return totalScore;
        }

        private int ScoreSpare(Frame frame, int roll1, int roll2, int totalScore)
        {
            int nextBall = NextBall(frame.Roll1BallIndex + 2);
            frame.Score.RollScore = roll1 + roll2 + nextBall;
            totalScore = totalScore + frame.Score.RollScore;
            frame.Score.TotalScore = totalScore;
            return totalScore;
        }


    }
}
